package com.mtnz.njk.Service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.mtnz.njk.Mapper.*;
import com.mtnz.njk.Util.History;
import com.mtnz.njk.Util.MapDistance;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.model.AskModel;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @Description: 提问业务层
 * @Author: ZPX
 * @CreateDate: 2019/7/30 16:21
 * @Version: 1.0
 */
@Service
public class AskService {
    @Autowired
    AskMapper askMapper;//提问

    @Autowired
    CommunityUserMapper communityUserMapper;

    @Autowired
    CommunityUserInfoMapper communityUserInfoMapper;

    @Autowired
    PraiseAskMapper praiseAskMapper;

    @Autowired
    CollectionAskMapper collectionAskMapper;

    @Autowired
    AskImgMapper askImgMapper;

    @Autowired
    UserTaskMapperr userTaskMapperr;

    @Autowired
    CountCommunityMapper countCommunityMapper;

    @Autowired
    UserTaskCountMapper userTaskCountMapper;

    @Autowired
    CommentAskMapper commentAskMapper;

    @Autowired
    CommentAskImgMapper commentAskImgMapper;

    @Autowired
    HistoryMapper historyMapper;


    /**
     * 发布提问
     */
    @Transactional
    public ResponseResult saveAsk(String message, String userId, String img, String lat, String lng) throws Exception {
        String location = "";
        String inform = "";
        String askId = IdUtil.simpleUUID();
        AskEntity askEntity = new AskEntity();
        NjkUserEntity njkUserEntity = communityUserMapper.selectByPrimaryKey(userId);
        //判断内容是否为空
        if (message != null && message.length() == 0) {
            return new ResponseResult(ResponseMessage.INCOMPLETE_INFORMATION);
        } else {
            if (lat != null && lat.length() > 4 && lng != null && lng.length() > 4) {
                location = MapDistance.getCoordinate3(lng, lat);
            } else {
                location = "农极客";
            }
            //保存提问信息

            askEntity.setAskId(askId);
            askEntity.setCreateDate(DateUtil.now());
            askEntity.setUserId(userId);
            askEntity.setViews("0");
            askEntity.setReply("0");
            askEntity.setMonth("");
            askEntity.setAddress(location);
            askEntity.setExamine("0");
            askEntity.setStatus("0");
            askEntity.setMessage(message.replace("!==!", "\n"));
            askEntity.setCrop("");
            askEntity.setAppStatus(0);
            askEntity.setShareViews(0);
            askEntity.setClickViews(0);
            askMapper.insert(askEntity);

            //*****************增加用户积分*****************

            Example example = new Example(UserTaskEntity.class);
            example.createCriteria().andEqualTo("userId", userId);
            List<UserTaskEntity> userTaskEntities = userTaskMapperr.selectByExample(example);
            if (userTaskEntities.size() > 0 && userTaskEntities != null) {
                UserTaskEntity userTaskEntity = userTaskEntities.get(0);
                Integer.parseInt(userTaskEntity.getQuizStatus().toString());
                Integer quizNum = Integer.parseInt(userTaskEntity.getQuizNum().toString()) + 1;

                //判断今天是否已完成 任务
                if (quizNum <= 8) {
                    CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
                    countCommunityEntity.setCommunityType(2);
                    countCommunityEntity.setCreateTime(new Date());
                    countCommunityEntity.setUserId(userId);
                    countCommunityEntity.setNum("1");
                    countCommunityEntity.setCommunityId(askId);
                    countCommunityEntity.setNews("发布提问");
                    countCommunityEntity.setOrderNum("");
                    countCommunityMapper.insert(countCommunityEntity);
                    //增加积分
                    njkUserEntity.setIntegral(njkUserEntity.getIntegral() + 1);
                    //增加总积分
                    njkUserEntity.setTotalIntegral(njkUserEntity.getTotalIntegral() + 1);
                    communityUserMapper.updateByPrimaryKey(njkUserEntity);
                    //添加用户任务
                    userTaskEntity.setUserId(userId);
                    userTaskEntity.setQuizNum(quizNum);
                    userTaskEntity.setQuizStatus(1);
                    userTaskMapperr.updateByPrimaryKey(userTaskEntity);
                    //添加单个任务
                    UserTaskCountEntity userTaskCountEntity = new UserTaskCountEntity();
                    userTaskCountEntity.setUserId(userId);
                    userTaskCountEntity.setTaskType(3);
                    userTaskCountEntity.setCreateTime(new Date());
                    userTaskCountMapper.insert(userTaskCountEntity);
                    inform = "1";
                }
            }
        }
        //保存到图片表
        AskImgEntity askImgEntity = new AskImgEntity();
        if (img != null && img != "" && !"".equals(img)) {
            String[] imgs = img.split(",");
            List<String> strings = Arrays.asList(imgs);
            for (int i = 0; i < strings.size(); i++) {
                askImgEntity.setAskId(askId);
                askImgEntity.setImg(strings.get(i));
                askImgEntity.setSort(String.valueOf(i + 1));
                askImgMapper.insert(askImgEntity);
            }
        }
        return new ResponseResult(ResponseMessage.OK,inform);
    }

    /**
     * 关注提问取消关注
     */
    @Transactional
    public ResponseResult collectionAsk(String status, String askId, String userId) throws Exception {
        CollectionAskEntity collectionAskEntity = new CollectionAskEntity();
        //封装结果集
        String collection = "0";
        if ("1".equals(status)) {
            if (collectionAskMapper.findCollection(userId, askId) == null) {
                //保存关注信息
                collectionAskEntity.setCollectionAskId(IdUtil.randomUUID());
                collectionAskEntity.setAskId(askId);
                collectionAskEntity.setStatus("1");
                collectionAskEntity.setUserId(userId);
                collectionAskEntity.setCreateDate(DateUtil.now());
                collectionAskMapper.insert(collectionAskEntity);
            }
            collection = "1";
        } else {
            collectionAskMapper.deleteCollection(userId, askId);
        }
        return new ResponseResult(ResponseMessage.OK, collection);
    }

    /**
     * 点赞提问
     */
    @Transactional
    public ResponseResult praiseAsk(String askId, String userId) throws Exception {
        AskEntity askEntity = askMapper.selectByPrimaryKey(askId);
        //封装结果集
        Map map = new HashMap<>();

        //查询是否有该用户对该文章的点赞记录
        Example example = new Example(PraiseAskEntity.class);
        example.createCriteria().andEqualTo("askId", askId)
                .andEqualTo("userId", userId);
        List<PraiseAskEntity> praiseAskEntities = praiseAskMapper.selectByExample(example);
        if (praiseAskEntities != null && praiseAskEntities.size() > 0) {

            //如果找到了这条记录，则删除该记录，同时文章的点赞数减1
            PraiseAskEntity praiseAskEntity = praiseAskEntities.get(0);
            praiseAskEntity.getAskId();
            praiseAskEntity.getUserId();

            //删除记录
            praiseAskMapper.deletePraiseAsk(praiseAskEntity);

            //文章点赞数减1，查询时使用Mysql行级锁解决并发覆盖问题
            if (Integer.parseInt(askEntity.getViews())>0) {
                Integer i = Integer.parseInt(askEntity.getViews()) - 1;
                askEntity.setViews(String.valueOf(i));
                askEntity.setStatus("0");
                askMapper.updateByPrimaryKey(askEntity);
            }
        } else {
            PraiseAskEntity praiseAskEntity = new PraiseAskEntity();
            //如果没有找到这条记录，则添加这条记录，同时文章点赞数加1
            praiseAskEntity.setAskId(askId);
            praiseAskEntity.setUserId(userId);
            //添加记录
            praiseAskMapper.insert(praiseAskEntity);
            //文章点赞数加1，查询时使用Mysql行级锁解决并发覆盖问题
            Integer i = Integer.parseInt(askEntity.getViews()) + 1;
            askEntity.setViews(String.valueOf(i));
            askEntity.setViews(String.valueOf(i));
            askEntity.setStatus("1");
            askMapper.updateByPrimaryKey(askEntity);
        }
        map.put("status", askEntity.getStatus());
        map.put("views", askEntity.getViews());
        return new ResponseResult(ResponseMessage.OK, map);
    }

    /**
     * 提问详情
     *
     * @return
     */
    public ResponseResult showAsk(String askId,String userId) throws Exception {
        //获取提问相关信息
        AskModel askModel = askMapper.showAsk(askId);


        //增加点击数
        AskEntity askEntity = new AskEntity();
        if (askModel.getClickViews()!=null&&!"".equals(askModel.getClickViews())){
            askEntity.setAskId(askModel.getAskId());
            askEntity.setClickViews(askModel.getClickViews() + 1);
            askMapper.updateByPrimaryKeySelective(askEntity);
        }
        //获取用户信息
        NjkUserEntity njkUserEntity = communityUserMapper.selectByPrimaryKey(askModel.getUserId());
        askModel.setName(njkUserEntity.getNickName());
        //获取用户扩展信息
        Example example = new Example(NjkUserInfoEntity.class);
        example.createCriteria().andEqualTo("userId", njkUserEntity.getUserId());
        List<NjkUserInfoEntity> njkUserInfoEntities = communityUserInfoMapper.selectByExample(example);
        NjkUserInfoEntity njkUserInfoEntity = njkUserInfoEntities.get(0);
        askModel.setImg(njkUserInfoEntity.getImg());
        //点赞
        PraiseAskEntity byId1 = praiseAskMapper.findById(askId, userId);
        if (byId1 != null) {
            askModel.setZan("1");
        } else {
            askModel.setZan("0");
        }
        //关注
        CollectionAskEntity collection = collectionAskMapper.findCollection(userId, askId);
        if (collection != null) {
            askModel.setCollection("1");
        } else {
            askModel.setCollection("0");
        }
        new Thread(new History(askModel.getMessage(), askId, "1", "问答", userId,
                "http://m.nongjike.cn/NJK/static/jsp/tiwen.html?TIWEN_ID=" + askId, historyMapper)).start();
        //获取提问图
        List<AskImgEntity> byId = askImgMapper.findById(askId);
        askModel.setTimg(byId);
        return new ResponseResult(ResponseMessage.OK, askModel);
    }
}
